let fs = require('fs');
let path = require('path');
let router = require('koa-router')();


function getFiles(dir) {

    let file = fs.readdirSync(dir);

    return file.filter((x) => {
        return x.endsWith('.js') && x !== "index.js";
    });

}

function getRouters(files) {
    files.map((x) => {

        let routerObj = require(path.join(__dirname, x));

        for (let r in routerObj) {
            let type = routerObj[r][0];
            let fn = routerObj[r][1];

            if (type == "get") {
                router.get(r, fn);
            } 
            else if(type == "post") {
                router.post(r, fn);
            }
            else if(type == "delete") {
                router.delete(r, fn);
            }
            else if(type == "put") {
                router.put(r, fn);
            }else{
                console.log("路由类型有误");
            }
        }
    });
}

module.exports = function (dirName) {
    dirName = dirName || __dirname;

    let files = getFiles(dirName);

    getRouters(files)

    return router.routes();
}